package connectors;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import utils.ObjectUtils;
import utils.StringUtils;
import model.DocumentEA;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class OfficeConnector {
	
     
	private ArrayList<DocumentEA> model;
	public OfficeConnector(String absoluteFilePath) {
		try {

			FileInputStream file = new FileInputStream(new File(
					absoluteFilePath));

			// Get the workbook instance for XLS file
			XSSFWorkbook workbook = new XSSFWorkbook(file);

			// Get first sheet from the workbook
			XSSFSheet sheet = workbook.getSheetAt(0);

			// Iterate through each rows from first sheet
			Iterator<Row> rowIterator = sheet.iterator();
			while (rowIterator.hasNext()) {
				Row row = rowIterator.next();

				// For each row, iterate through each columns
				Iterator<Cell> cellIterator = row.cellIterator();

				DocumentEA docEA = new DocumentEA();
				while (cellIterator.hasNext()) {

					XSSFCell cell = (XSSFCell) cellIterator.next();
					if (cell.getColumnIndex() == 0) {
						docEA.setName(processCell(cell));
					}
					if (cell.getColumnIndex() == 1) {
						docEA.setVersion(processCell(cell));
					}
					if (cell.getColumnIndex() == 2) {
						docEA.setType(processCell(cell));
					}
					if (cell.getColumnIndex() == 3) {
						docEA.setNewOrChange(processCell(cell));
					}

				}
				if (ObjectUtils.propsNotNullandEmpty(docEA)) {
					model.add(docEA);
				}

			}
			file.close();

			// creating docuemnt EA model

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private String processCell(XSSFCell cell) {
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_BOOLEAN: {
			return StringUtils.SafeString(String.valueOf(cell
					.getBooleanCellValue()));
		}
		case Cell.CELL_TYPE_NUMERIC: {
			return StringUtils.SafeString(String.valueOf(cell
					.getNumericCellValue()));
		}
		case Cell.CELL_TYPE_STRING: {
			return StringUtils.SafeString(String.valueOf(cell
					.getStringCellValue()));
		}
		default: {
			return "";
		}
		}

	}

	public ArrayList<DocumentEA> getModel() {
		return model;
	}

}
